package com.hb.unic.core.dispatcher;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.lang.NonNull;

import com.hb.unic.core.context.Application;

import lombok.extern.slf4j.Slf4j;

/**
 * 事件工具类
 *
 * @since v1.0，2023/8/25 22:50，create by Mr.Huang.
 */
@SuppressWarnings("all")
@Slf4j
public class EventUtils {

    /**
     * 缓存
     */
    private static final Map<String, Object> HANDLER_CACHE = new HashMap<>();

    /**
     * 事件转发
     *
     * @param handlerClass 事件处理类
     */
    public static <T extends IEventHandler<E>, E extends IEventArgs> void dispatch(@NonNull Class<T> handlerClass) {
        dispatch(handlerClass, null);
    }

    /**
     * 事件转发
     *
     * @param handlerClass 事件处理类
     * @param eventArgs 事件参数
     */
    public static <T extends IEventHandler<E>, E extends IEventArgs> void dispatch(@NonNull Class<T> handlerClass,
        E eventArgs) {
        String handlerClassName = handlerClass.getName();
        // 先从缓存里面取
        List<T> handlers = (List<T>)HANDLER_CACHE.get(handlerClassName);
        if (handlers == null) {
            handlers = Application.getContext().getBeanList(handlerClass);
            handlers.sort((o1, o2) -> {
                Order order1 = AnnotationUtils.findAnnotation(o1.getClass(), Order.class);
                int orderValue1 = order1 == null ? 0 : order1.value();
                Order order2 = AnnotationUtils.findAnnotation(o2.getClass(), Order.class);
                int orderValue2 = order2 == null ? 0 : order2.value();
                return orderValue1 - orderValue2;
            });
            HANDLER_CACHE.put(handlerClassName, handlers);
        }
        // 执行所有处理器
        for (IEventHandler<E> handler : handlers) {
            log.info("Execute handler: {}", handler.getClass().getSimpleName());
            handler.execute(eventArgs);
        }
    }

}
